﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Win32;

namespace VSTweaker
{
    public class ComponentType
    {
        public ComponentType(string descriptionValueName, string parentKeyName, string vsVersion, string instance)
        {
            _descriptionValueName = descriptionValueName;
            _parentKeyName = parentKeyName;
            _vsVersion = vsVersion;

            this.instance = instance;
        }

        public IEnumerable<RegistryItem> RegistryItems
        {
            get
            {
                if (_items == null)
                {
                    Init();
                }
                return _items;
            }
        }

        private string _descriptionValueName;
        private string _parentKeyName;
        private string _vsVersion;
        private IEnumerable<RegistryItem> _items;
        private string instance;

        public void Init()
        {
            var regItems = new List<RegistryItem>();

            var hklm = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry64);

            using (var vsKey = hklm.OpenSubKey(string.Format("Software\\Microsoft\\VisualStudio\\{0}{1}_Config", _vsVersion, this.instance)))
            {
                if (vsKey == null) return;
                using (var packageKey = vsKey.OpenSubKey(_parentKeyName))
                {
                    if (packageKey == null) return;
                    var subKeys = packageKey.GetSubKeyNames();
                    foreach (var subKey in subKeys)
                    {
                        var subhKey = packageKey.OpenSubKey(subKey);

                        var valueNames = subhKey.GetValueNames();
                        foreach (var valueName in valueNames)
                        {
                            if (_descriptionValueName == valueName)
                            {
                                var value = subhKey.GetValue(valueName);
                                if (String.IsNullOrEmpty(value.ToString()))
                                {
                                    value = "<Unknown>";
                                }

                                var registryItem = new RegistryItem(subhKey, value.ToString());
                                regItems.Add(registryItem);
                            }
                        }
                    }
                }
            }

            regItems.Sort((x, y) => x.Description.CompareTo(y.Description));

            _items = regItems;
        }

        public override string ToString()
        {
            return _parentKeyName;
        }
    }
}
